package com.ruoyi.monitor.controller;

import com.ruoyi.project.setting.security.LoginUser;
import com.ruoyi.project.setting.security.service.TokenService;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.framework.web.controller.BaseController;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 在线用户监控
 *
 * @author dy
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController {

    private final TokenService tokenService;

    @PreAuthorize("@ss.hasPermi('monitor:online:list')")
    @GetMapping("/list")
    public R getLoginUsers(String ipaddr, String userName) {
        List<Object> onlineUsers = tokenService.getOnlineUsers();
        List<LoginUser> copy = $.copy(onlineUsers, LoginUser.class);
        return success(copy.stream()
                .filter(o -> {
                    if ($.isNotBlank(ipaddr)) {
                        return o.getIpaddr().equals(ipaddr);
                    }
                    return true;
                })
                .filter(o -> {
                    if ($.isNotBlank(userName)) {
                        return o.getSysUser().getUserName().equals(userName);
                    }
                    return true;
                })
                .map(LoginUser::toLoginUserVO)
                .collect(Collectors.toList()));
    }

    /**
     * 强退用户
     */
    @SysLog(title = "在线用户", businessType = BusinessTypeEnum.FORCE)
    @PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
    @DeleteMapping("/{tokenId}")
    public R forceLogout(@PathVariable String tokenId) {
        tokenService.delLoginUser(tokenId);
        return success();
    }
}
